package cn.dao789.mvvm;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import cn.dao789.R;
import cn.dao789.model.UserModel;

/**
 * MVVM架构中的View
 * 负责UI的渲染和用户交互，通过ViewModel获取和操作数据
 */
public class MvvmActivity extends AppCompatActivity {
    // View组件
    private EditText editTextUsername;
    private EditText editTextEmail;
    private Button buttonSave;
    private TextView textViewUserInfo;
    
    // ViewModel
    private UserViewModel userViewModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvvm);
        
        // 初始化View组件
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextEmail = findViewById(R.id.editTextEmail);
        buttonSave = findViewById(R.id.buttonSave);
        textViewUserInfo = findViewById(R.id.textViewUserInfo);
        
        // 获取ViewModel实例
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        
        // 观察LiveData，当数据变化时自动更新UI
        userViewModel.getUserLiveData().observe(this, new Observer<UserModel>() {
            @Override
            public void onChanged(UserModel userModel) {
                // 更新UI显示用户信息
                if (userModel != null) {
                    textViewUserInfo.setText("用户信息：\n" +
                            "ID: " + userModel.getUserId() + "\n" +
                            "用户名: " + userModel.getUsername() + "\n" +
                            "邮箱: " + userModel.getEmail());
                }
            }
        });
        
        // 设置事件监听
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 调用ViewModel的方法处理业务逻辑
                userViewModel.saveUser(
                        editTextUsername.getText().toString(),
                        editTextEmail.getText().toString());
                
                // 显示保存成功提示
                Toast.makeText(MvvmActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
            }
        });
    }
}